<?php  namespace App\Api\Models;

use Input;
use App\Api\Models\Orders;
use App\Api\Models\User;
use App\Api\Models\Cabinet;
use App\Api\Models\CabinetCell;
use App\Api\Models\WxUser;

use Log;
class Goods extends BaseModel{
    
	//表明
	protected $table = 'goods';
	//主键
	protected $primaryKey = 'id';
    //获取用户可提现余额
    public function getGoodsInterface() {
        $mobile = Input::get('mobile');
        $eno = Input::get('eno');
        $bno = Input::get('bno');
        if(!$eno){
            $retArr["msg"]= "未获取到箱体号";
            $retArr["result"] = 0;
            return $retArr;
        }
        if(!$bno){
            $retArr["msg"]= "未获取到柜号";
            $retArr["result"] = 0;
            return $retArr;
        }
        if(!$mobile){
            $retArr["msg"]= "请传入手机号";
            $retArr["result"] = 0;
            return $retArr;
        }
        $user = User::select('*')
                ->where('phone','=',$mobile)
                ->where('status','=',1)
                ->where('is_delete','=',0)
                ->first();
        if(!$user){
//            $retArr["msg"]= "请传入手机号";
//            $retArr["result"] = 0;
//            return $retArr;
            $user = new User();
            $user->status = 1;
            $user->reg_time = time();
            $user->phone = $mobile;
            $user->save();
        }
        $box1 = Cabinet::select('*')
                ->where('code','=',$eno)
                ->where('is_delete','=',0)
                ->first();
        if(!$box1){
            $retArr["msg"]= "未获取到箱体号";
            $retArr["result"] = 0;
            return $retArr;
        }
        $cell = CabinetCell::select('*')
                ->where('cabinet_id','=',$box1->id)
                ->where('code','=',$bno)
                ->where('is_delete','=',0)
                ->first();
        if(!$cell){
            $retArr["msg"]= "未获取到柜号";
            $retArr["result"] = 0;
            return $retArr;
        }
        $status= 0;
        $statusMsg="可以使用";
        if($cell->status == 1){
            //被占用
            $status= 2;
            $statusMsg= "设备已经被被人租用";
            
        }else if($cell->status == 2){
            //保修中
            $status= 3;
            $statusMsg= "设备故障，正处于等待维修状态";
        }
        $good = Goods::select('*')
                ->where('status','=',1)
                ->where('is_delete','=',0)
                ->where('id','=',$cell->goods_id)
                ->first();
        $price = Price::select('*')
                ->where('is_delete','=',0)
                ->where('id','=',$cell->price_id)
                ->first();
        $order = Orders::select('*')
                ->where('is_delete','=',0)
//                ->where('user_id','=',$user->id)
                ->where('cabinet_id','=',$box1->id)
                ->where('cell_id','=',$cell->id)
                ->where('status','=',2)
                ->first();
        if($order && $order->user_id == $user->id){
            $status= 1;//自己租用中
        }
        //deposit
        if((!$user->client_id || $user->is_bind != 2) && $user->deposit <=0){
            $payMsg="个人需押金¥298.00元,绑定企业有优惠哦~！";
        }
        
        $retArr["msg"]= "获取成功";
        $retArr["result"] = 1;
        $retArr["mobile"] = $mobile;
        $retArr["pFee"] = 2;//企业支付部分
        $retArr["cFee"] = 3;//个人支付部分
        $retArr["CustomerID"] = $user->client_id;
        $retArr["CustomerNM"] = 0;
        $retArr["modernID"] = isset($good->id)?$good->id:0;;
        $temp['ID'] = isset($good->id)?$good->id:0;
        $temp['goodsNM'] = isset($good->name)?$good->name:"空";
        $temp['Logo'] = isset($good->icon)?$good->icon:"";
        $temp['upload'] = "upload";
        $temp['func'] = "产品功能";
        $temp['clsID'] = "部位Id";
        $temp['clsNM'] = "身体部位";
        $temp['brandID'] = "品牌Id";
        $temp['brandNM'] = "品牌名";
        $temp['jtxt'] = $good->introduction;
//        jtxt
        if($temp['Logo'] && !strpos("http",$temp['Logo'])){
            $temp['Logo'] = env("QINIU_IMG_HOST").$temp['Logo'];
        }
            //QINIU_IMG_HOST

        $retArr["GoodsData"][] = $temp;
        $retArr["status"] = $status;//盒子状态
        $retArr["statusmsg"] = $statusMsg;
        $retArr["zc"] = "元";//价格
        $retArr["starttime"] = isset($order->start_time)?date("Y-m-d H:i:s",$order->start_time):date("Y-m-d H:i:s",time());
        $retArr["payMsg"] = "付款信息";
//        Log::info("获取商品信息参数=". json_encode($retArr));
        
        
//        "{\"result\":1,\"mobile\":\"".$mobile."\",\"pFee\":".$this->getCustFee($mobile,$this->getUserCustomer($mobile)).",
//        \"cFee\":".(3-$this->getCustFee($mobile,$this->getUserCustomer($mobile))).",\"CustomerID\":".$this->getUserCustomer($mobile).",
//        \"CustomerNM\":\"".$this->getCustomerNM($this->getUserCustomer($mobile))."\",\"modernID\":".$this->getCustomerModern($this->getUserCustomer($mobile)).",
//        \"GoodsData\":[{\"ID\":\"".$data["ID"]."\",\"goodsNM\":\"".$data["goodsNM"]."\",\"Logo\":\"".base_url()."upload/".$data["Logo"]."\",
//        \"jtxt\":\"".$data["jtxt"]."\",\"func\":\"".$data["Function"]."\",\"clsID\":\"".$data["clsID"]."\",
//        \"clsNM\":\"".$this->getClsNM($data["clsID"])."\",\"brandID\":".$data["brandID"].",
//        \"brandNM\":\"".$this->getBrandNM($data["brandID"])."\"}]"
        return $retArr;
    }
    //
    public function getStatus() {
        $mobile = Input::get('mobile');
        $eno = Input::get('eno');
        $bno = Input::get('bno');
        if(!$eno){
            $retArr["msg"]= "未获取到箱体号";
            $retArr["result"] = 0;
            return $retArr;
        }
        if(!$bno){
            $retArr["msg"]= "未获取到柜号";
            $retArr["result"] = 0;
            return $retArr;
        }
        if(!$mobile){
            $retArr["msg"]= "请传入手机号";
            $retArr["result"] = 0;
            return $retArr;
        }
        $user = User::select('*')
                ->where('phone','=',$mobile)
                ->where('status','=',1)
                ->where('is_delete','=',0)
                ->first();
        if(!$user){
            $retArr["msg"]= "请传入手机号";
            $retArr["result"] = 0;
            return $retArr;
        }
        $box1 = Cabinet::select('*')
                ->where('code','=',$eno)
                ->where('is_delete','=',0)
                ->first();
        if(!$box1){
            $retArr["msg"]= "未获取到箱体号";
            $retArr["result"] = 0;
            return $retArr;
        }
        $cell = CabinetCell::select('*')
                ->where('cabinet_id','=',$box1->id)
                ->where('code','=',$bno)
                ->where('is_delete','=',0)
                ->first();
        if(!$cell){
            $retArr["msg"]= "未获取到柜号";
            $retArr["result"] = 0;
            return $retArr;
        }
        if($cell->status == 0){
            $retArr["msg"]= "已归还";
            $retArr["result"] = 1;
            $retArr["status"] = 0;
            return $retArr;
        }else if($cell->status == 1){
            $retArr["msg"]= "未归还";
            $retArr["result"] = 1;
            $retArr["status"] = 1;
            return $retArr;
        }else if($cell->status == 2){
            $retArr["msg"]= "报修中";
            $retArr["result"] = 1;
            $retArr["status"] = 0;
            return $retArr;
        }
    }
    //获取商品列表
    public function goodslst() {
//        $mobile = Input::get('mobile');
//        if(!$mobile){
//            $retArr["msg"]= "请传入手机号";
//            $retArr["result"] = 0;
//            return $retArr;
//        }
        $goodsList = Goods::select('*')
                ->where('status','=',1)
                ->where('is_delete','=',0)
                ->get();
        $data['data'] = [];
        if($goodsList){
            foreach ($goodsList as $key=>$val){
                $temp = [];
                $temp['No'] = (int)$key + 1;
                $temp['ID'] = $val->id;
                $temp['goodsNM'] = $val->name;
                $temp['Logo'] = $val->icon;
                $temp['isSell'] = $val->is_sell;
                $temp['inventory'] = $val->inventory;
                if($temp['Logo'] && !strpos("http",$temp['Logo'])){
                    $temp['Logo'] = env("QINIU_IMG_HOST").$temp['Logo'];
                }
                $temp['jtxt'] = $val->introduction;
                $temp['txt'] = "txt";
                $temp['clsID'] = "clsID";
                $temp['clsNM'] = "晒耳";
                $temp['brandID'] = "brandID";
                
                $temp['brandNM'] = "商城";
                if($val->price > 0){
                    $temp['Price'] = $val->price;
                }else{
                    $temp['Price'] = 600;
                }
                $temp['Jf'] = $val->jf?$val->jf:600;
                
                $data['data'][] = $temp;
            }
        }
        $retArr["msg"]= "获取成功!";
        $retArr["result"] = 1;
        return array_merge($retArr,$data);
    }
    //获取商品详情
    public function getGoodsInfo() {
//        $mobile = Input::get('mobile');
        $goodsId = Input::get('id');
        $goods = Goods::select('*')
                ->where('id','=',$goodsId)
                ->where('status','=',1)
                ->where('is_delete','=',0)
                ->first();
        $temp = [];
        if($goods){
            $temp['ID'] = $goods->id;
            $temp['goodsNM'] = $goods->name;
            $temp['Logo'] = $goods->icon;
            $temp['isSell'] = $goods->is_sell;
            $temp['inventory'] = $goods->inventory;
            if($temp['Logo'] && !strpos("http",$temp['Logo'])){
                $temp['Logo'] = env("QINIU_IMG_HOST").$temp['Logo'];
            }
            $temp['jtxt'] = $goods->introduction;
            $temp['txt'] = "txt";
            $temp['clsID'] = "clsID";
            $temp['clsNM'] = "晒耳";
            $temp['brandID'] = "brandID";

            $temp['brandNM'] = "商城";
            if($goods->price > 0){
                $temp['Price'] = $goods->price;
            }else{
                $temp['Price'] = 600;
            }
            $temp['Jf'] = $goods->jf?$goods->jf:600;
        }
//            echo "{ \"msg\": \"获取成功\", \"result\": 1,\"ID\":\"".$data["ID"]."\",\"goodsNM\":\"".$data["goodsNM"]."\",\"Logo\":\"".base_url()."/upload/".$data["Logo"]."\",\"jtxt\":\"".$data["jtxt"]."\",\"clsID\":\"".$data["clsID"]."\",\"clsNM\":\"".$this->getClsNM($data["clsID"])."\",\"brandID\":".$data["brandID"].",\"brandNM\":\"".$this->getBrandNM($data["brandID"])."\",\"Price\":".$data["Price"].",\"Jf\":".$data["Jf"]."}";
        $retArr["msg"]= "获取成功!";
        $retArr["result"] = 1;
        return array_merge($retArr,$temp);
    }
    public function doReturn() {
//        $mobile = Input::get('mobile');
        $eno = Input::get('eno');
        $bno = Input::get('bno');
//        if(!$mobile){
//            $retArr["msg"]= "请传入手机号";
//            $retArr["result"] = 0;
//            return $retArr;
//        }
        if(!$eno){
            $retArr["msg"]= "未获取到箱体号";
            $retArr["result"] = 0;
            return $retArr;
        }
        if(!$bno){
            $retArr["msg"]= "未获取到柜号";
            $retArr["result"] = 0;
            return $retArr;
        }
//        $user = User::select('*')
//                ->where('phone','=',$mobile)
//                ->where('status','=',1)
//                ->where('is_delete','=',0)
//                ->first();
//        if($user){
            $box = Cabinet::select('*')
                ->where('code','=',$eno)
                ->where('is_delete','=',0)
                ->first();
            if(!$box){
                Log::info('1');
                $retArr["msg"]= "未获取到箱体号";
                $retArr["result"] = 0;
                return $retArr;
            }
            $cell = CabinetCell::select('*')
                    ->where('cabinet_id','=',$box->id)
                    ->where('code','=',$bno)
                    ->where('is_delete','=',0)
                    ->first();
            if(!$cell){
                Log::info('1');
                $retArr["msg"]= "未获取到柜号";
                $retArr["result"] = 0;
                return $retArr;
            }
            
            //-点击归还
            $cell->status = 0;
            $cell->save();
            
            $order = Orders::select('*')
//                    ->where('user_id','=',$cell->user_id)
                    ->where('type','=',1)
                    ->where('cabinet_id','=',$box->id)
                    ->where('cell_id','=',$cell->id)
                    ->where('is_delete','=',0)
                    ->where('status','=',2)
                    ->orderBy('id','desc')
                    ->first();
            
            if(!$order){
                $order = Orders::select('*')
                    ->where('type','=',1)
                    ->where('cabinet_id','=',$box->id)
                    ->where('cell_id','=',$cell->id)
                    ->where('is_delete','=',0)
                    ->where('status','=',1)
                    ->orderBy('id','=','desc')
                    ->first();
                if(!$order->end_time){
                    $order->end_time = time();
                    $order->save();
                }
                Log::info('1234');
                $retArr["msg"]= "请传入正确手机号";
                $retArr["result"] = 0;
                return $retArr;
            }
            $user = User::select('*')
                ->where('id','=',$order->user_id)
                ->where('status','=',1)
                ->where('is_delete','=',0)
                ->first();
            $endTime = time();
            $arr = $this->countFee($cell->price_id,$order->start_time,$endTime,$user->client_id);
            if(!$arr){
                Log::info('价格异常，请联系管理员');
                $retArr["msg"]= "价格异常，请联系管理员~！";
                $retArr["result"] = 0;
                return $retArr;
            }
            if($user->client_id && $user->is_bind == 2){//企业用户
                //个人支付  + 企业支付
                $user->balance = $user->balance - $arr['pFee'];//可能为负数
                $user->save();
                $client = Client::select('*')
                        ->where('id','=',$user->client_id)
                        ->where('status','=',1)
                        ->where('is_delete','=',0)
                        ->first();
                $client->balance = $client->balance - $arr['cFee'];//可能为负
                $client->save();
                //$arr['minute'] 分钟怎么记录
            }else{
//                //priceId = 1 时，为标准收费 7-22
//                $arr = $this->countFee(1,$order->start_time,$endTime,$user->client_id);
                //对内对外同一套收费标准
                $arr = $this->countFee($cell->price_id,$order->start_time,$endTime,$user->client_id);
//              订单完成
                $user->balance = $user->balance - $arr['pFee'];//可能为负数
                $user->save();
            }
            $order->amount = $arr['pFee'];
            $order->status = 1;
            $order->pay_type = 1;
            $order->end_time = $endTime;
            $order->save();
            
            $addScore = 5;
//            1、单次使用+5分，超过30min + 5分，超过1小时 +10分，单次使用最多 15分； 上限 100分
            if($order->end_time - $order->start_time > 3600 ){
                $addScore = 15;
            }else if ($order->end_time - $order->start_time > 1800) {
                $addScore = 10;
            }
            //添加积分
            if($order->open_id){
                $wxUser = WxUser::select("*")
                    ->where('open_id','=',$order->open_id)
                    ->first();
                if($wxUser){
                    $wxUser->score_jf = $wxUser->score_jf + $addScore;
                    $wxUser->save();
                    
                    $scoreRecord =new ScoreRecord();
                    $scoreRecord->user_id = $order->user_id;
                    $scoreRecord->wx_user_id = $wxUser->id;
                    $scoreRecord->reason = '尊敬的用户您本次使用,为您增加'.$addScore.'积分';
                    $scoreRecord->score = $addScore;
                    $scoreRecord->type = 1;
                    $scoreRecord->save();
                }
            }
            
            
//            $ret = with(new User())->ReturnOpenBox($eno,$bno);
//        }else{
//            $retArr["msg"]= "柜子异常，请联系管理员~！";
//            $retArr["result"] = 0;
//            return $retArr;
//        }
    }
    //获取已经产生的费用
    public function SumFee() {
        $mobile = Input::get('mobile');
        $eno = Input::get('eno');
        $bno = Input::get('bno');
        if(!$mobile){
            $retArr["msg"]= "请传入手机号";
            $retArr["result"] = 0;
            return $retArr;
        }
        if(!$eno){
            $retArr["msg"]= "未获取到箱体号";
            $retArr["result"] = 0;
            return $retArr;
        }
        if(!$bno){
            $retArr["msg"]= "未获取到柜号";
            $retArr["result"] = 0;
            return $retArr;
        }
        $user = User::select('*')
                ->where('phone','=',$mobile)
                ->where('status','=',1)
                ->where('is_delete','=',0)
                ->first();
        if($user){
            $box = Cabinet::select('*')
                ->where('code','=',$eno)
                ->where('is_delete','=',0)
                ->first();
            if(!$box){
                $retArr["msg"]= "未获取到箱体号";
                $retArr["result"] = 0;
                return $retArr;
            }
            $cell = CabinetCell::select('*')
                    ->where('cabinet_id','=',$box->id)
                    ->where('code','=',$bno)
                    ->where('is_delete','=',0)
                    ->first();
            if(!$cell){
                $retArr["msg"]= "未获取到柜号";
                $retArr["result"] = 0;
                return $retArr;
            }
            $orders = Orders::select('*')
                    ->where('user_id','=',$user->id)
                    ->where('type','=',1)
                    ->where('cabinet_id','=',$box->id)
                    ->where('cell_id','=',$cell->id)
                    ->where('is_delete','=',0)
                    ->where('status','=',1)
                    ->orderBy('id',"desc")
                    ->take(1)
                    ->get();
//            Log::info("获取的订单=". json_encode($orders));
            if(!$orders){
                $retArr["msg"]= "请传入正确手机号";
                $retArr["result"] = 0;
                return $retArr;
            }
            $starTime = 0;
            $endTime = 0;
            foreach ($orders as $key=>$val){
                $endTime = isset($val->start_time)?$val->end_time:0;
                $starTime = isset($val->start_time)?$val->start_time:0;
            }
            $arr = $this->countFee($cell->price_id,$starTime,$endTime,$user->client_id);
            if(!$arr){
                $retArr["msg"]= "价格异常，请联系管理员~！";
                $retArr["result"] = 0;
                return $retArr;
            }
            $retArr["msg"]= "获取成功";
            $retArr["mobile"] = $mobile;
            $retArr["customerID"] = isset($arr['CustomerID'])?$arr['CustomerID']:0;
            $retArr["pFee"] = isset($arr['pFee'])?$arr['pFee']:0;
            $retArr["cFee"] = isset($arr['cFee'])?$arr['cFee']:0;
            $retArr["minute"] = isset($arr['minute'])?$arr['minute']:0;
            $retArr["result"] = 1;
            return $retArr;
        }
//        echo "{ \"msg\": \"获取成功\",\"mobile\":\"".$mobile."\",
//        \"customerID\":\"".$usr["customerID"]."\",\"pFee\":".$arr["pFee"].",
//        \"cFee\":".$arr["cFee"].",\"minute\":".$arr["minute"].", \"result\":1}";
        $retArr["msg"]= "没有进行中的订单!";
        $retArr["result"] = 0;
        return $retArr;
    }
    //计算消费
    public function countFee($priceId,$startTime,$endTime,$CustomerID) {
        Log::info("priceId=".$priceId."-开始时间=".$startTime."-结束时间=".$endTime);
        if(!is_numeric($startTime) || !is_numeric($endTime)){
            return false;
        }
        $price = Price::select('*')
            ->where('is_delete','=',0)
            ->where('id','=',$priceId)
            ->first();
        if(!$price){
            return false;
        }
        $time = 0;
        $pFee = 0;
        if($price->price){
            $priceArr = json_decode($price->price,TRUE);
            if(!is_array($priceArr)){
                return false;
            }
            $time = floor(((int)$endTime - (int)$startTime)*100/60)/100;//单位秒
            //[{"price":"0","beginTime":"0","endTime":"10080","unit":"60"}]
            foreach ($priceArr as $val){
                if(!isset($val['price']) || !isset($val['beginTime']) || !isset($val['endTime']) || !isset($val['unit'])){
                    return false;
                }
                if($time > $val['beginTime'] && $time <= $val['endTime']){
                    $unit = ceil($time/$val['unit']);//用了多少单位,向上取整
                    $pFee = $unit * $val['price'];
                    Log::info("租用费用=".$pFee."-使用单位=".$unit."-单位价格=".$val['price']);
                    break;
                }
            }
        }
        return array('cFee'=>0,'pFee'=>$pFee,'minute'=>$time,'CustomerID'=>$CustomerID);
    }
}